<template>
    <div>
        <!--NavBar 导航栏-->
        <van-nav-bar
                :title="type != 2 ? '注册' : '修改密码'"
                left-text="返回"
                left-arrow
                @click-left="onClickLeft"
        />
        <!--NoticeBar 通知栏-->
        <van-notice-bar mode="closeable" v-show="type == 1">
            温馨提示：如果邮箱已存在且验证码无误，则直接修改为当前输入的密码
        </van-notice-bar>
        <!-- Form 表单 -->
        <van-form @submit="onSubmit">
            <van-field
                    v-model="account"
                    name="account"
                    label="邮箱"
                    placeholder="请输入您的邮箱.."
                    error-message-align="right"
                    :clearable="true"
                    :rules="[
                        { required: true, message: '邮箱必须' },
                        { validator:checkEmail, message: '邮箱格式错误' }
                    ]"
            />
            <van-field
                    v-model="code"
                    center
                    clearable
                    name="code"
                    label="邮箱验证码"
                    placeholder="code"
                    :rules="[
                        { required: true, message: '邮箱验证码必须' },
                    ]"
            >
                <template #button>
                    <span @click="onSendCode" class="sendCodeTips">{{sendCodeTips}}</span>
                </template>
            </van-field>
            <van-field
                    v-model="password"
                    type="password"
                    name="password"
                    label="密码"
                    placeholder="请输入密码.."
                    error-message-align="right"
                    :clearable="true"
                    :rules="[
                    { required: true, message: '密码必须' },
                    { validator:checkPassword, message: '密码必须由 4-16位字母、数字组成.' }
                    ]"
            />
            <van-field
                    v-model="re_password"
                    type="password"
                    name="re_password"
                    label="确认密码"
                    placeholder="请输入确认密码.."
                    error-message-align="right"
                    :clearable="true"
                    :rules="[
                    { validator:checkRePassword, message: '两次输入的密码不一致' }
                    ]"
            />
            <div  class="submit-btn">
                <van-button round block type="info" native-type="submit">
                    提交
                </van-button>
            </div>
        </van-form>
        <br/>
        <!-- 跳转路由 -->
        <div class="register-tips" v-show="type == 1">
            我已有账号？
            <router-link to="/login"><span class="a-text">前往登录</span></router-link>
        </div>
    </div>
</template>

<script>
    import Vue from 'vue';
    import {NavBar, NoticeBar, Form, Field, Toast, Image as VanImage} from 'vant';

    Vue.use(NavBar).use(Form).use(Toast).use(NoticeBar).use(VanImage).use(Field);

    var ERR_OK = 1;
    export default {
        name: "register",
        data() {
            return {
                account: "",
                code: "",
                password: "",
                re_password: "",
                // 可能的文案：发送、已发送300s、重新发送
                sendCodeTips: "发送",
                // 验证码发送状态，防止重复发送
                isSend: false,
                // 1:注册 2:修改密码
                type: 1
            }
        },
        mounted() {
            this.$store.commit("setPlayerStatus", false);
            this.$store.commit("setTabbarStatus", false);
            // 根据上级路由判断类型
            this.type = this.$route.params.type;
            // 填充最近提交的account
            var userInfo = JSON.parse(localStorage.getItem("userInfo"));
            if (userInfo && userInfo.email !== "undefined") {
                this.account = userInfo.email;
            } else {
                this.account = localStorage.getItem("RecentInputAccount") || "";
            }
            // 验证码失效时间
            var second = this.$store.state.SendCodeSecond;
            if (second > 0) {
                this.isSend = true;
                this.setSendCodeTips(second);
            }
        },
        methods: {
            // 返回
            onClickLeft() {
                // 可能返回到 /my
                this.$store.commit("setTabbarStatus", true);
                this.$router.go(-1);
            },
            // 验证邮箱合法
            checkEmail(email) {
                return !!email.match(/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/)
            },
            // 验证密码合法
            checkPassword(password) {
                return !!password.match(/^[\w]{4,12}$/);
            },
            // 验证确认密码合法
            checkRePassword(re_password) {
                return this.password === re_password;
            },
            // 发送邮箱验证码
            onSendCode() {
                if (this.isSend) {
                    return;
                }
                this.$http.get("/account/sendCodeToEmail?email=" + this.account)
                    .then((response) => {
                        var rs = response.data;
                        if (rs.code === ERR_OK) {
                            this.isSend = true;
                            var second = 600;
                            Toast.success("发送成功");
                            this.setSendCodeTips(second);
                        }
                    });

            },
            // 修改验证码按钮文案
            setSendCodeTips(second) {
                const timer = setInterval(() => {
                    second--;
                    if (second) {
                        this.sendCodeTips = "已发送 " + second + "s";
                    } else {
                        this.isSend = false;
                        clearInterval(timer);
                        this.sendCodeTips = "重新发送";
                    }
                    this.$store.commit("setSendCodeSecond", second);
                }, 1000);
            },
            // 提交注册或修改
            onSubmit(values) {
                var that = this;
                var qs = require('qs');
                var params = qs.stringify(values);
                this.$http.post("/account/register", params).then((response) => {
                    var rs = response.data;
                    if (rs.code !== ERR_OK) {
                        Toast.fail(rs.msg);
                    } else {
                        Toast.success(rs.msg);
                        setTimeout(function () {
                            // 清空登陆并跳转登陆页面
                            localStorage.removeItem("userInfo");
                            that.$router.push('/login');
                        }, 2000);
                    }
                });
                localStorage.setItem("RecentInputAccount", values.account);
            }
        }
    }
</script>

<style scoped>
    .register-tips {
        text-align: center;
        color: #7e8c8d;
    }

    .a-text {
        color: #00ccff;
        text-decoration: underline;
        font-style: oblique;
        line-height: 35px;
    }

    .sendCodeTips {
        border: 2px solid #07c160;
        padding: 10px 5px;
        border-radius: 5%;
        background: #07c160;
        color: #fff;
    }

    .submit-btn{
        margin: 20px 0;
    }
</style>